import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:ifly_speech_recognition/ifly_speech_recognition.dart';
import 'package:mobcommonlib/mobcommonlib.dart';
import 'package:mobpush_plugin/mobpush_custom_message.dart';
import 'package:mobpush_plugin/mobpush_notify_message.dart';

import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sph_driver/AppConfig/ShowDialog.dart';
import 'package:sph_driver/Login/GuidePage.dart';
import 'package:sph_driver/Login/LoginVIewController.dart';
import 'AppConfig/LocalStorage.dart';




import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'l10n/messages.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart'
    show BMFMapSDK, BMF_COORD_TYPE;
Future<void> main() async {

  WidgetsFlutterBinding.ensureInitialized(); //必须要添加这个进行初始化 否则下面会错误
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    runApp(const MyApp());
  });
  /// 动态申请定位权限
  requestPermission();

  LocationFlutterPlugin myLocPlugin = LocationFlutterPlugin();
  Mobcommonlib.submitPolicyGrantResult(true, null);
  /// 设置用户是否同意SDK隐私协议
  /// since 3.1.0 开发者必须设置
  BMFMapSDK.setAgreePrivacy(true);
  myLocPlugin.setAgreePrivacy(true);
  // 百度地图sdk初始化鉴权
  if (Platform.isIOS) {
    myLocPlugin.authAK('PwxADGzFEbO9AvA8mdAWu5juvInEFXYT');
    BMFMapSDK.setApiKeyAndCoordType('PwxADGzFEbO9AvA8mdAWu5juvInEFXYT', BMF_COORD_TYPE.BD09LL);
    //设置远程推送环境，向用户授权 开发环境 false, 线上环境 true
    MobpushPlugin.setAPNsForProduction(false);
  }
  else if (Platform.isAndroid) {

    /// 初始化获取Android 系统版本号，如果低于10使用TextureMapView 等于大于10使用Mapview
    await BMFAndroidVersion.initAndroidVersion();
    // Android 目前不支持接口设置Apikey,
    // 请在主工程的Manifest文件里设置，详细配置方法请参考官网(https://lbsyun.baidu.com/)demo
    BMFMapSDK.setCoordType(BMF_COORD_TYPE.BD09LL);
  }
  // // LocationFlutterPlugin myLocPlugin = LocationFlutterPlugin();
  // // 设置是否隐私政策
  // myLocPlugin.setAgreePrivacy(true);
  //
  // BMFMapSDK.setAgreePrivacy(true);
  // // WidgetsFlutterBinding.ensureInitialized();
  // // await SharedPreferences.getInstance();
  // if (Platform.isIOS) {
  //   /// 设置ios端ak, android端ak可以直接在清单文件中配置
  //   myLocPlugin.authAK('PwxADGzFEbO9AvA8mdAWu5juvInEFXYT');
  //
  // }

}
// 动态申请定位权限
void requestPermission() async {
  // 申请权限
  bool hasLocationPermission = await requestLocationPermission();
  if (hasLocationPermission) {
    // 权限申请通过
  } else {}
}
/// 申请定位权限
/// 授予定位权限返回true， 否则返回false
Future<bool> requestLocationPermission() async {
  //获取当前的权限
  var status = await Permission.location.status;
  if (status == PermissionStatus.granted) {
    //已经授权
    return true;
  } else {
    //未授权则发起一次申请
    status = await Permission.location.request();
    if (status == PermissionStatus.granted) {
      return true;
    } else {
      return false;
    }
  }
}
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  //setLocale 方法用于从应用的任何位置切换语言环境。它通过找到最近的 _MyAppState 实例，并调用其 setLocale 方法来实现切换语言功能。
  static void setLocale(BuildContext context, Locale newLocale) {
    _MyAppState state = context.findAncestorStateOfType<_MyAppState>()!;
    state.setLocale(newLocale);
  }

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  Future<void> _requestLocationPermission() async {
    final status = await Permission.location.request();
    if (status == PermissionStatus.granted) {
      // 定位权限已授予
    } else {
      // 用户拒绝了定位权限
      // 可以在这里做一些处理，例如提示用户手动授予权限
    }
  }
  Locale _locale = const Locale('zh', ''); // 默认语言为中文
//_loadLocaleFromPreferences 方法从 SharedPreferences 中加载用户偏好设置的语言环境。如果存在保存的语言代码，就将其更新到 _locale 变量中。
  Future<void> _loadLocaleFromPreferences() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? languageCode = prefs.getString('languageCode');
    if (languageCode != null) {
      setState(() {
        _locale = Locale(languageCode, '');
      });
    }
  }

//_saveLocaleToPreferences 方法用于将选择的语言环境保存到 SharedPreferences 中，以便下次启动应用时可以加载该语言环境。
  Future<void> _saveLocaleToPreferences(Locale locale) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('languageCode', locale.languageCode);
  }

  void setLocale(Locale newLocale) {
    _saveLocaleToPreferences(newLocale);
    setState(() {
      _locale = newLocale;
    });
  }
  String satoken="";
  String _sdkVersion = 'Unknown';
  String _registrationId = 'Unknown';
  late Timer timer;
  // 上一次点击返回键的时间
  DateTime? lastPressed;
  @override
  void initState() {
    super.initState();
    // _loadLocaleFromPreferences();

    _requestLocationPermission();
    //上传隐私协议许可
    MobpushPlugin.updatePrivacyPermissionStatus(true).then((value) {
      print(">>>>>>>>>>>>>>>>>>>updatePrivacyPermissionStatus:" +
          value.toString());
    });
    if (Platform.isIOS) {
      //设置地区：regionId 默认0（国内），1:海外
      MobpushPlugin.setRegionId(0);
      MobpushPlugin.registerApp("369bba7c10764", "2ce734bf0f1ad6b35e44a186d0ff1130");
    }
    initPlatformState();
    if (Platform.isIOS) {
      MobpushPlugin.setCustomNotification();
      MobpushPlugin.setAPNsForProduction(true);
    }
    MobpushPlugin.addPushReceiver(_onEvent, _onError);
    getLocAction();


  }
  @override
  void dispose() {
    timer.cancel(); // 取消定时器
    super.dispose();
  }
  void getLocAction()async{
    String? token=await TokenManager.getToken();
    if(token!=null&&token!=""){
      // 获取一次位置
      _determinePosition();
      // 设置定时器，每 5 分钟获取一次位置
      timer = Timer.periodic(Duration(minutes: 5), (Timer t) => _determinePosition());
    }
  }
  //定时器获取位置
  Future<void> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    // 检查位置服务是否启用
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      setState(() {
      });
      return;
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        setState(() {
          showLocFirstDialog(context);
        });
        return;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      setState(() {
        showLocDialog(context);
      });
      return;
    }

    // 当一切都准备好时，获取位置
    Position position = await Geolocator.getCurrentPosition();
    setState(() {
      LongitudeManager.saveLongitude(position.longitude.toString());
      LatitudeManager.saveLatitude(position.latitude.toString());
      print("Latitude: ${position.latitude}, Longitude: ${position.longitude}");
    });
  }
  Future<void> initPlatformState() async {
    String sdkVersion;
    try {
      sdkVersion = await MobpushPlugin.getSDKVersion();
    } on PlatformException {
      sdkVersion = 'Failed to get platform version.';
    }
    try {
      Future.delayed(Duration(milliseconds: 500), () {
        MobpushPlugin.getRegistrationId().then((Map<String, dynamic> ridMap) {
          print(ridMap);
          setState(() {
            _registrationId = ridMap['res'].toString();
            print('------>#### registrationId: ' + _registrationId);
          });
        });
      });
    } on PlatformException {
      _registrationId = 'Failed to get registrationId.';
    }
  }
  void _onEvent(dynamic event) {
    print('>>>>>>>>>>>>>>>>>>>>>>>>>>>onEvent:' + event.toString());
    setState(() {
      Map<String, dynamic> eventMap = json.decode(event as String);
      Map<String, dynamic> result = eventMap['result'];
      int action = eventMap['action'];

      switch (action) {
        case 0:
          MobPushCustomMessage message =
          new MobPushCustomMessage.fromJson(result);
          showDialog(
              context: context,
              builder: (context) {
                return AlertDialog(
                  content: Text(message.content),
                  actions: <Widget>[
                    TextButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        child: Text("确定")
                    )
                  ],
                );
              });
          break;
        case 1:
          MobPushNotifyMessage message =
          new MobPushNotifyMessage.fromJson(result);
          break;
        case 2:
          MobPushNotifyMessage message =
          new MobPushNotifyMessage.fromJson(result);
          break;
      }
    });
  }
  void _onError(dynamic event) {
    setState(() {
      print('>>>>>>>>>>>>>>>>>>>>>>>>>>>onError:' + event.toString());
    });
  }
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        print("再按一次退出");
        // 获取当前时间
        final now = DateTime.now();
        // 如果 lastPressed 为空或者间隔时间超过 2 秒，则更新 lastPressed 并提示用户
        if (lastPressed == null || now.difference(lastPressed!) > Duration(seconds: 2)) {
          lastPressed = now;
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('再按一次退出'),
              duration: Duration(seconds: 2),
            ),
          );
          return false; // 不退出
        }
        return true; // 退出应用
      },
      child:  ScreenUtilInit(
        designSize: const Size(360, 690),
        minTextAdapt: true,
        splitScreenMode: true,
        builder: (context , child) {
          return CupertinoApp(
            localizationsDelegates: const [
              GlobalMaterialLocalizations.delegate,
              AppLocalizationsDelegate(),
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,

            ],
            supportedLocales: [
              Locale('en'),
              Locale('zh'),
            ],
            locale: _locale,

            debugShowCheckedModeBanner: false,
            title: 'First Method',
            // You can use the library anywhere in the app even in theme

            builder: (context, child) =>
                MediaQuery(data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true), child: child!),
            home: child,
          );
        },
        child: GuidePage(),

      ),
    );

  }
}

